package com.bytech.admin.biz.exception.handler;

import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.bytech.admin.biz.exception.BlogAdminNotLoginException;
import com.bytech.admin.biz.exception.BlogAdminRuntimeException;
import com.bytech.common.biz.entity.base.BlogResultStatus;

/**
 * 管理后台业务异常处理
 * SpringMVC 返回的异常视图由 AdminSpringMVCConfig 配置拦截处理
 *
 * @Author Zhao
 * @Create 2021/8/9 11:30
 * @see com.bytech.admin.config.AdminSpringMVCConfig
 */
@ControllerAdvice
public class BlogAdminExceptionHandler {

    /**
     * 需要立即返回登录页的业务异常
     */
    @ExceptionHandler(BlogAdminNotLoginException.class)
    public String handleNotLoginException(BlogAdminNotLoginException exception, HttpServletResponse response, RedirectAttributes redirectAttributes) throws IOException {
        redirectAttributes.addFlashAttribute("errorMsg", exception.getMessage());
        return "redirect:/login";
    }

    /**
     * 其他未知异常统一返回 500 页
     */
    @ExceptionHandler(BlogAdminRuntimeException.class)
    public String handleBlogAdminRuntimeException(BlogAdminRuntimeException exception, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        BlogResultStatus resultStatus = exception.getResultStatus();
        // TODO 自定义处理博客业务异常 现在默认返回 500 页，并在上面打印异常信息
        redirectAttributes.addFlashAttribute("resultStatus", resultStatus);
        return "redirect:/error/500";
    }
}
